import TemplatePort from "../template.js";
import { MathUtils } from "../../utils/utils.js";
import { verify } from "./verify.js";
import config from "../../config/config.js";

class Email extends TemplatePort {
  constructor(validator) {
    super(validator, false);
  }

  /**
   * @api {post} /mail/sendCode 邮箱验证
   * @apiDescription 验证邮箱是否可用，并发送邮箱验证码，并缓存5分钟
   * @apiGroup 邮箱
   * @apiBody {String} email 邮箱地址
   * @apiBody {String} [id] 用户ID
   * @apiUse templatePort
   */
  async sendCode(req) {
    let data = req.body;
    let ip = req.get("host");
    this.toVerify(data);
    let user = await this.store.user.findOne({ email: data.email });
    let userid = user ? user._id.toHexString() : null;
    console.log(userid, data.id);
    if (userid != data?.id) throw new Error("邮箱已被注册");

    // 生成验证码, 发送验证码邮件
    let code = MathUtils.random(100000, 999999);
    code = String(code);
    await this.transport.sendMail({
      to: data.email,
      subject: "邮箱验证",
      text: `
        验证码：${code}，请不要泄露给他人。
        有效期五分钟，请在五分钟内完成验证。
      `,
    });

    // 存储验证码信息
    await this.store.vcode.updateOne(
      { ip },
      {
        ip,
        code,
        email: data.email,
        expire: Date.now() + config.mailExpire,
      },
      true
    );

    return this.resT(null, "验证码已发送，请注意查收");
  }
}

export default new Email(verify);
